package com.v1.video.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.CarouselAdapter;
import com.v1.video.adapter.RecommendAdapter2;
import com.v1.video.db.dao.RecommendTB;
import com.v1.video.domain.Carousel;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.RecommendAdEntity;
import com.v1.video.domain.RecommendEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.interfaces.OnChannelListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.view.CircleFlowIndicator;
import com.v1.video.view.ViewFlow;

import java.util.List;

/**
 * 推荐频道
 * 
 * @author wangfang
 * 
 */
public class RecommendFragment extends V1BaseFragment {

	private static final String TAG = "RecommendFragment";
	private View mView, mViewHeader, mEmptyView;
	private ListView mListView;
	private PullToRefreshListView mRefreshListView;
	private LayoutInflater mInflater;
	private ViewFlow mViewflow;
	private CircleFlowIndicator mFlowIndicator;
	private RecommendAdapter2 mAdapter;
	private String mCid;
	private List<RecommendTB> mLstData;
	private List<Carousel> mLstCarousel;
	private CarouselAdapter mImageAdapter;
	private boolean isLoad = true;
	private OnChannelListener mOnChannelListener;

	public static RecommendFragment newInstance(String tag) {
		RecommendFragment f = new RecommendFragment();
		Bundle bundle = new Bundle();
		bundle.putString("tag", tag);
		f.setArguments(bundle);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mInflater = inflater;
		mView = inflater.inflate(R.layout.fragment_recommend, container, false);
		initView();
		setListener();
		initData();
		return mView;
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("首页-推荐");
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("首页-推荐");
	}

	@Override
	public void refresh(Object tag) {
		// TODO Auto-generated method stub
		super.refresh(tag);
		if (isLoad == true) {
			isLoad = false;
			if (mRefreshListView != null) {
				mRefreshListView.doPullRefreshing(50);
			}
		}
	}

	public void setOnChannelListener(OnChannelListener onChannelListener) {
		mOnChannelListener = onChannelListener;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		Logger.i(TAG, "setUserVisibleHint--" + isVisibleToUser + "--" + mCid);
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mViewHeader = mInflater
				.inflate(R.layout.fragment_classify_header, null);
		mRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.lv_listView);
		mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setMode(Mode.PULL_FROM_START);
		mListView.addHeaderView(mViewHeader);
		mViewflow = (ViewFlow) mViewHeader.findViewById(R.id.vf_viewflow);
		RelativeLayout mLayViewflow = (RelativeLayout) mViewHeader
				.findViewById(R.id.lay_viewflow);
		mViewflow.setViewGroup(mListView);
		int width = Utils.getScreenWidth(this.getActivity());
		//		int height = width / 2;
		int height = (int) (width * 1.06);
		//		mLayViewflow.setLayoutParams(new LinearLayout.LayoutParams(width,
		//				height));
		mFlowIndicator = (CircleFlowIndicator) mViewHeader
				.findViewById(R.id.flowIndicator);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setListener() {
		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
			}
		});
		mRefreshListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshBase refreshView) {
				if (Helper.checkConnection(RecommendFragment.this.getActivity())) {
					getAd();
					getServerData();
				} else {
					getLocalData();
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}
		});

		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});

		mViewflow.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				Logger.i(TAG, "mAdvFlow.onScrollStateChanged");
				// TODO Auto-generated method stub
				try {
					int pos = mViewflow.getSelectedItemPosition();
					if (mLstCarousel == null || mLstCarousel.size() <= 0) {
						return;
					}
					if (pos < 0) {
						return;
					}
					pos = pos % mLstCarousel.size();
					Logger.i(TAG, "pos3333333==" + pos);
					if (pos >= mLstCarousel.size()) {
						pos = 0;
					}
					if (pos < 0) {
						return;
					}
					String typeStr = mLstCarousel.get(pos).getAt();
					if (TextUtils.isEmpty(typeStr)) {
						return;
					}
					String title = mLstCarousel.get(pos).getTitle();
					Logger.i(TAG, "title==" + title);
					if (Constant.VIDEO_TYPE_8.equals(typeStr)) {
						RequestEngine request = new RequestEngine();
						request.sendADVLogToServer(getActivity(),
								Constant.STATE_ADV_CZBM_2 + "",
								Constant.STATE_ADV_CZSX_2 + "_"
										+ mLstCarousel.get(pos).getTid(), ""
												+ Constant.STATE_ADV_CZJG_1);
						if (mLstCarousel.get(pos).getAdShow() != null
								&& mLstCarousel.get(pos).getAdShow().length() > 5) {
							RequestEngine request1 = new RequestEngine();
							request1.askThirdADVLink(getActivity(),
									mLstCarousel.get(pos).getAdShow());
						}
						if (pos == 0 || pos == 1) {
							String adid = "";
							if (pos == 0) {
								adid = "8";
							} else {
								adid = "9";
							}
							new NetEngine().AdUpToServer(getActivity(),
									mLstCarousel.get(pos).getAdid(), LoginInfo
									.getInstance().getUserId(), adid,
									"1", "-1");
						}
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "mAdvFlow_onScroll");
			}
		});
	}
	
	private void getLocalData(){
		String recomend = AppContext.getPreference("recommend");
		if(!TextUtils.isEmpty(recomend)){
			RecommendEntity entity =new Gson().fromJson(recomend, RecommendEntity.class);
			if (entity != null && entity.getBody() != null) {
				if (mAdapter != null) {
					mAdapter.setLstData(entity.getBody()
							.getDatalist());
				}
				mLstCarousel = entity.getBody().getFocus();
				showViewFlow();
			}
		}
	}

	private void initData() {
		mCid = getArguments().getString("tag");
		clickStatistics(Constant.HOME_CLASSIFICATION_ID, "首页推荐频道-" + mCid);
		mAdapter = new RecommendAdapter2(getActivity());
		mAdapter.setOnChannelListener(mOnChannelListener);
		mListView.setAdapter(mAdapter);
		if (mRefreshListView != null) {
			mRefreshListView.doPullRefreshing(100);
		}
	}

	/**
	 * 设置空的界面显示
	 */
	private void setEmptyView() {
		View view = mListView.getEmptyView();
		if (view == null) {
			mListView.setEmptyView(mEmptyView);
		}
	}

	/**
	 * 加载本地文件
	 */
	private void loadCachedData() {
		String json = Utility.ReadTxtFile(getActivity(),
				"RecommendCarouselCache.txt");
		if (!TextUtils.isEmpty(json)) {
			Gson gson = new Gson();
			// mCarouselLst = gson.fromJson(json, CarouselLst.class);
			showViewFlow();
		}
	}

	/**
	 * 缓存本地文件
	 * 
	 * @param mCarousel
	 */
	private void saveloadCachedData(List<Carousel> mCarousel) {
		// if (mCarouselLst != null) {
		// if (mCarousel != null) {
		// mCarouselLst.setFocus(mCarousel);
		// }
		// Gson gson = new Gson();
		// String jsonStr = gson.toJson(mCarouselLst);
		// Utility.CacheData(RecommendFragment.this.getActivity(),
		// "RecommendCarouselCache.txt", jsonStr);
		// }
	}

	private void getAd(){
		String url = String.format(V1VideoHttpApi.RECOMMEND_AD());
		RequestManager.getInstance().getRequest(getActivity(),url,RecommendAdEntity.class,"recommend", new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code, String message,
					String keyId) {
				// TODO Auto-generated method stub
				//				try {
				try {
					if(object != null ){
						RecommendAdEntity adEntity = (RecommendAdEntity) object;
						if(adEntity != null && adEntity.getBody() != null && adEntity.getBody().getData() != null){
							if (mAdapter != null) {
								mAdapter.setAdLstData(adEntity.getBody().getData().getCarousels());
							}
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.e("ex", e.getMessage());
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub

			}

		});
	}

	/**
	 * 获取服务器推荐列表数据
	 */
	private void getServerData() {
		String url = String.format(V1VideoHttpApi.HOME_RECOMMEND_LIST(),
				Constant.DEVICEID);
		Logger.i(TAG, "推荐列表url=" + url);
		RequestManager.getInstance().getRequest(this.getActivity(), url,
				RecommendEntity.class, mCid, new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String keyId) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				try {
					if (object != null) {
						RecommendEntity entity = (RecommendEntity) object;
						if (entity != null && entity.getBody() != null) {
							if (mAdapter != null) {
								mAdapter.setLstData(entity.getBody()
										.getDatalist());
							}
							mLstCarousel = entity.getBody().getFocus();
							showViewFlow();
							saveLocalData(entity);
						}
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				setEmptyView();
				Logger.i(TAG, message);
			}

		});
	}
	private void saveLocalData(RecommendEntity entity){
		String recommendData =	new Gson().toJson(entity);
		AppContext.savePreference("recommend", recommendData);
	}


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isLoad = true;
		if (mAdapter != null) {
			mAdapter = null;
		}
		if (mLstData != null) {
			mLstData.clear();
			mLstData = null;
		}
		RequestManager.getInstance().requestCancel(this.getActivity(), mCid);
	}

	/**
	 * 显示轮播图
	 */
	private void showViewFlow() {
		if (mLstCarousel != null && mLstCarousel.size() > 0) {
			try {
				int perWidth = (int) this.getResources().getDimension(
						R.dimen.cf_indicator_per_width);
				int width = mLstCarousel.size() * perWidth;
				ViewGroup.LayoutParams params= mFlowIndicator.getLayoutParams();
				params.width = width;
				mFlowIndicator.setLayoutParams(params);
				mImageAdapter = new CarouselAdapter(getActivity());
				mImageAdapter.setLstData(mLstCarousel);
				mViewflow.setmSideBuffer(mLstCarousel.size());
				mViewflow.setAdapter(mImageAdapter);
				mViewflow.setFlowIndicator(mFlowIndicator);
				if (mLstCarousel.size() > 1) {
					mViewflow.setTimeSpan(10000);
					mViewflow.setSelection(mLstCarousel.size() * 1000); // 设置初始位置
					mViewflow.startAutoFlowTimer(); // 启动自动播放
				} else {
					mViewflow.stopAutoFlowTimer();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				setEmptyView();
				showToast(R.string.net_no_click);
				break;
			default:
				break;
			}
		}
	};
}
